package com.maodou.core.utils

import android.app.Activity
import android.app.Application
import android.content.Context
import android.os.Bundle
import java.lang.ref.WeakReference
import javax.inject.Inject
import javax.inject.Singleton

/**
 * 全局Activity提供者
 * 用于在非UI层（如ViewModel、Repository等）中获取当前前台Activity
 * 解决权限检查等需要Activity Context的场景
 */
@Singleton
class ActivityProvider @Inject constructor(
    private val application: Application
) {
    
    private var currentActivityRef: WeakReference<Activity>? = null
    private var isRegistered = false
    
    private val activityLifecycleCallbacks = object : Application.ActivityLifecycleCallbacks {
        override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {}
        
        override fun onActivityStarted(activity: Activity) {}
        
        override fun onActivityResumed(activity: Activity) {
            currentActivityRef = WeakReference(activity)
        }
        
        override fun onActivityPaused(activity: Activity) {}
        
        override fun onActivityStopped(activity: Activity) {}
        
        override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {}
        
        override fun onActivityDestroyed(activity: Activity) {
            if (currentActivityRef?.get() == activity) {
                currentActivityRef = null
            }
        }
    }
    
    /**
     * 初始化Activity生命周期监听
     * 通常在Application中调用
     */
    fun initialize() {
        if (!isRegistered) {
            application.registerActivityLifecycleCallbacks(activityLifecycleCallbacks)
            isRegistered = true
        }
    }
    
    /**
     * 获取当前前台Activity
     * @return 当前前台Activity，如果没有则返回null
     */
    fun getCurrentActivity(): Activity? {
        return currentActivityRef?.get()
    }
    
    /**
     * 获取当前前台Activity，如果没有则抛出异常
     * @return 当前前台Activity
     * @throws IllegalStateException 如果当前没有前台Activity
     */
    fun requireCurrentActivity(): Activity {
        return getCurrentActivity() 
            ?: throw IllegalStateException("No current activity available. Make sure there is a foreground activity.")
    }
    
    /**
     * 获取Application Context
     * @return Application Context
     */
    fun getApplicationContext(): Context = application
    
    /**
     * 获取当前Activity Context，如果没有则返回Application Context
     * @return Activity Context 或 Application Context
     */
    fun getContext(): Context {
        return getCurrentActivity() ?: application
    }
    
    /**
     * 静态访问方法
     */
    companion object {
        @Volatile
        private var INSTANCE: ActivityProvider? = null
        
        /**
         * 初始化ActivityProvider实例
         * 通常在Application中调用
         */
        fun initialize(instance: ActivityProvider) {
            INSTANCE = instance
            instance.initialize()
        }
        
        /**
         * 获取当前前台Activity
         * @return 当前前台Activity，如果没有则返回null
         */
        fun getCurrentActivity(): Activity? {
            return INSTANCE?.getCurrentActivity()
        }
        
        /**
         * 获取当前前台Activity，如果没有则抛出异常
         * @return 当前前台Activity
         * @throws IllegalStateException 如果ActivityProvider未初始化或没有前台Activity
         */
        fun requireCurrentActivity(): Activity {
            return INSTANCE?.requireCurrentActivity() 
                ?: throw IllegalStateException("ActivityProvider not initialized. Make sure to call initialize() in Application.")
        }
        
        /**
         * 获取Application Context
         * @return Application Context
         */
        fun getApplicationContext(): Context {
            return INSTANCE?.getApplicationContext() 
                ?: throw IllegalStateException("ActivityProvider not initialized. Make sure to call initialize() in Application.")
        }
        
        /**
         * 获取当前Context（优先Activity，其次Application）
         * @return Context
         */
        fun getContext(): Context {
            return INSTANCE?.getContext() 
                ?: throw IllegalStateException("ActivityProvider not initialized. Make sure to call initialize() in Application.")
        }
    }
}